package com.leetcode;
import java.util.ArrayList;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author LongYu
 * @date 2022/7/19 11:08
 * <p>
 * 使用 双指针
 */
public class D_56 {
    public static void main(String[] args) {
//        [[1,3],[2,6],[8,10],[15,18]]
        int[][] ints = {{1,3},{2,6},{8,10},{15,18}};

        int[][] merge = new D_56().merge(ints);
        System.out.println(Arrays.deepToString(merge));

    }



    public int[][] merge(int[][] arr) {
        if (arr == null || arr.length <= 1)
            return arr;
        List<int[]> list = new ArrayList<>();
        Arrays.sort(arr,(a,b)->a[0]-b[0]);
        int i = 0;
        int n = arr.length;
        while (i < n) {
            int left = arr[i][0];
            int right = arr[i][1];
            while (i < n - 1 && right >= arr[i + 1][0]) {
                right = Math.max(right, arr[i + 1][1]);
                i++;
            }
            list.add(new int[]{left, right});
            i++;
        }
        return list.toArray(new int[list.size()][2]);
    }
}
